package com.njym.quartz.service;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.njym.entity.*;
import com.njym.payment.alipay.service.AliPayService;
import com.njym.payment.wxpay.service.WxService;
import com.njym.service.PlatformBusinessRecService;
import com.njym.service.SysOrganizationService;
import com.njym.service.SysPaymentModeService;
import com.njym.tradeStatusConfig.WxTradeStatus;
import com.njym.webservice.WebService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

@Component
public class ReconciliationsService {

    @Autowired
    private SysOrganizationService sysOrganizationService;

    @Autowired
    private SysPaymentModeService sysPaymentModeService;

    @Autowired
    private AliPayService aliPayService;

    @Autowired
    private WxService wxService;

    @Autowired
    private PlatformBusinessRecService platformBusinessRecService;

    private static final Logger LOGGER = LoggerFactory.getLogger(ReconciliationsService.class);

    @Autowired
    private WebService webService;

    /**
     * method: reconciliations
     *
     * @Description:
     * @param: [name]
     * @return: void
     * @author: yh
     * @date: 2018/9/14 11:04
     */
    public void reconciliations(String name) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        //此时打印它获取的是系统当前时间
        Calendar calendar = Calendar.getInstance();
        //得到前一天
        calendar.add(Calendar.DATE, -1);
        String billDate = sdf.format(calendar.getTime());
        Wrapper<SysOrganization> queryParams = new EntityWrapper<>();
        queryParams.orderBy("sort_no", true);
        queryParams.eq("deleted", 0);
        List<SysOrganization> sysOrganizationList = sysOrganizationService.selectList(queryParams);
        List<Object> list = new ArrayList<>();
        if (sysOrganizationList != null && sysOrganizationList.size() > 0) {
            for (SysOrganization sysOrganization : sysOrganizationList) {
                String dataUrl = sysOrganization.getDataUrl();
                if(StringUtils.isNotBlank(dataUrl) && !list.contains(dataUrl)){
                    list.add(dataUrl);
                    // TODO 获取机构的dataUrl从his取数据到中间表
                    String getDataResult = webService.getData(dataUrl, billDate, billDate);
                    if (!WxTradeStatus.SUCCESS.equals(getDataResult)) {
                        continue;
                    }
                }
                //遍历机构
                String orgId = sysOrganization.getId();
                Wrapper<SysPaymentMode> payModeParams = new EntityWrapper<>();
                payModeParams.orderBy("sort_no", true);
                payModeParams.eq("org_id", orgId);
                payModeParams.eq("deleted", 0);
                List<SysPaymentMode> sysPaymentModes = sysPaymentModeService.selectList(payModeParams);
                if (sysPaymentModes != null && sysPaymentModes.size() > 0) {
                    for (SysPaymentMode sysPaymentMode : sysPaymentModes) {
                        String modeId = sysPaymentMode.getId();
                        switch (sysPaymentMode.getModeCode()) {
                            case "alipay":
                                //下载支付宝账单
                                JSONObject jsonObject = aliPayService.aliPayBill(orgId, billDate);
                                String result = jsonObject.getString("result");
                                if (result.equals(WxTradeStatus.SUCCESS)) {
                                    String path = jsonObject.getString("path");
                                    //平台与支付宝对账
                                    aliPayService.reconciliationAliPayBill(orgId, modeId, path, billDate);
                                }
                                break;
                            case "wxpay":
                                wxService.downloadWxPayBill(orgId, modeId, billDate);
                                break;
                            default:
                                break;
                        }
                        //平台与机构对账
                        this.reconciliationPlatformOrgBill(orgId, modeId, billDate);
                    }
                }
                //aliPayService.
            }
        }
    }

    /**
     * method: reconciliationPlatformOrgBill
     *
     * @Description: 平台与机构对账
     * @param: [orgId, modeId, billDate]
     * @return: void
     * @author: yh
     * @date: 2018/9/13 17:31
     */
    private void reconciliationPlatformOrgBill(String orgId, String modeId, String billDate) {
        OrgBusinessRec orgBusinessRec = new OrgBusinessRec();
        Wrapper<OrgBusinessRec> orgParam = new EntityWrapper<>();
        orgParam.eq("org_id", orgId);
        orgParam.eq("mode_id", modeId);
        orgParam.between("billing_date", billDate + " 00:00:00", billDate + " 23:59:59");
        List<OrgBusinessRec> orgBusinessRecList = orgBusinessRec.selectList(orgParam);
        Wrapper<PlatformBusinessRec> queryParams = new EntityWrapper<>();
        queryParams.isNotNull("trade_no");
        queryParams.eq("org_id", orgId);
        queryParams.eq("mode_id", modeId);
        queryParams.between("trade_date", billDate + " 00:00:00", billDate + " 23:59:59");
        List<PlatformBusinessRec> platformBusinessRecList = platformBusinessRecService.selectList(queryParams);
        for (PlatformBusinessRec platformBusinessRec : platformBusinessRecList) {
            String outTradeNo = platformBusinessRec.getOutTradeNo();
            boolean existFlag = false;
            for (OrgBusinessRec orgRec : orgBusinessRecList) {
                if (outTradeNo.equals(orgRec.getOutTradeNo())) {
                    existFlag = true;
                    orgRec.setAccountFlag(Byte.valueOf("1"));
                    orgRec.updateById();
                }
            }
            Date nowDate = new Date();
            platformBusinessRec.setAccountFlag(Byte.valueOf("1"));
            platformBusinessRec.setAccountDate(nowDate);
            if (existFlag) {
                platformBusinessRec.setAbnormalFlag(Byte.valueOf("0"));
            } else {
                //异常记录 长款
                platformBusinessRec.setAbnormalFlag(Byte.valueOf("1"));
                ReconcileAbnormalRec reconcileAbnormalRec = new ReconcileAbnormalRec();
                reconcileAbnormalRec.setOrgId(platformBusinessRec.getOrgId());
                reconcileAbnormalRec.setChannelId(platformBusinessRec.getChannelId());
                reconcileAbnormalRec.setModeId(platformBusinessRec.getModeId());
                reconcileAbnormalRec.setRecType(platformBusinessRec.getRecType());
                reconcileAbnormalRec.setTradeNo(platformBusinessRec.getTradeNo());
                reconcileAbnormalRec.setOutTradeNo(platformBusinessRec.getOutTradeNo());
                reconcileAbnormalRec.setPlatformFee(platformBusinessRec.getTotalFee());
                reconcileAbnormalRec.setOrgFee(new BigDecimal(0).setScale(2, BigDecimal.ROUND_HALF_UP));
                reconcileAbnormalRec.setStatus(Byte.valueOf("1"));
                reconcileAbnormalRec.setCreateDate(platformBusinessRec.getCreateDate());
                reconcileAbnormalRec.insert();
            }
            platformBusinessRec.updateById();
        }
        for (OrgBusinessRec orgRec : orgBusinessRecList) {
            String orgOutTradeNo = orgRec.getOutTradeNo();
            boolean existFlag = false;
            if (orgRec.getAccountFlag() == 1) {
                break;
            }
            for (PlatformBusinessRec platformBusinessRec : platformBusinessRecList) {
                if (platformBusinessRec.getAccountFlag() == 1) {
                    break;
                }
                if (platformBusinessRec.getOutTradeNo().equals(orgOutTradeNo)) {
                    existFlag = true;
                    platformBusinessRec.setAccountFlag(Byte.valueOf("1"));
                    platformBusinessRec.setAccountDate(new Date());
                    platformBusinessRec.setAbnormalFlag(Byte.valueOf("0"));
                    platformBusinessRec.updateById();
                }
            }
            if (existFlag) {
                orgRec.setAccountFlag(Byte.valueOf("1"));
                orgRec.updateById();
            } else {
                ReconcileAbnormalRec reconcileAbnormalRec = new ReconcileAbnormalRec();
                reconcileAbnormalRec.setOrgId(orgRec.getOrgId());
                reconcileAbnormalRec.setChannelId(orgRec.getChannelId());
                reconcileAbnormalRec.setModeId(orgRec.getModeId());
                reconcileAbnormalRec.setTradeNo(orgRec.getTradeNo());
                reconcileAbnormalRec.setOutTradeNo(orgRec.getOutTradeNo());
                reconcileAbnormalRec.setPlatformFee(new BigDecimal(0).setScale(2, BigDecimal.ROUND_HALF_UP));
                reconcileAbnormalRec.setOrgFee(orgRec.getTotalFee());
                reconcileAbnormalRec.setStatus(Byte.valueOf("1"));
                reconcileAbnormalRec.setCreateDate(orgRec.getCreateDate());
                reconcileAbnormalRec.insert();
            }
            orgRec.setAccountFlag(Byte.valueOf("1"));
            orgRec.updateById();
        }
    }
}
